/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.payment.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.DateUtil;
import com.icinfo.cloud.provider.common.utils.ExcelUtils;
import com.icinfo.cloud.provider.peripheralinterface.electricinvoice.dto.ElectricInvoiceRequest;
import com.icinfo.cloud.provider.peripheralinterface.electricinvoice.service.IElectricInvoiceInterface;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.config.dto.ConfigPaymentChannelInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.mapper.SysDepartParamMapper;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.IConfigPaymentChannelInfoService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.config.vo.ConfigPaymentChannelInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseMainDetailAuxiliaryInfoRequest;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.*;
import com.icinfo.cloud.provider.punish.ucase.payment.enums.PayStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.payment.mapper.CasePaymentItemDetailMapper;
import com.icinfo.cloud.provider.punish.ucase.payment.mapper.CasePaymentMainRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.payment.mapper.CasePaymentResultRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentItemDetail;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentMainRecord;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentResultRecord;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentItemDetailService;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentMainRecordService;
import com.icinfo.cloud.provider.punish.ucase.payment.vo.*;
import com.icinfo.cloud.provider.punish.ucase.punishdecide.service.impl.PunishDecideServiceImpl;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 描述:  case_payment_main_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年03月01日
 */
@Service
@Slf4j
public class CasePaymentMainRecordServiceImpl extends MyBatisServiceSupport implements ICasePaymentMainRecordService {
    private static String CHANNEL_NO = "500000022";//todo 暂时写
    @Resource
    private CasePaymentMainRecordMapper casePaymentMainRecordMapper;
    @Resource
    private PunishDecideServiceImpl punishDecideServiceImpl;
    @Resource
    private IConfigPaymentChannelInfoService iConfigPaymentChannelInfoService;
    @Resource
    private ICasePartiesRecordService iCasePartiesRecordService;
    @Resource
    private CasePaymentItemDetailMapper casePaymentItemDetailMapper;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Resource
    private ICasePaymentItemDetailService iCasePaymentItemDetailService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICaseMainDetailAuxiliaryInfoService caseMainDetailAuxiliaryInfoService;
    @Resource
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Resource
    private ICaseMainDetailSimpleInfoService caseMainDetailSimpleInfoService;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private CasePaymentResultRecordMapper casePaymentResultRecordMapper;
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalInfoMapper;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private ICasePaymentItemDetailService casePaymentItemDetailService;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ICaseMainDetailInfoService caseMainDetailInfoService;
    @Resource
    private ICasePaymentMainRecordService casePaymentMainRecordService;
    @Resource
    private IElectricInvoiceInterface electricInvoiceInterface;
    @Value("${paymentCq.busUnpayDataSyncUrl}")
    private String busUnpayDataSyncUrl;
    @Value("${paymentCq.notifyUrl}")
    private String notifyUrl;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private SysDepartParamMapper sysDepartParamMapper;



    /**
     * 描述：查询缴款单信息
     *
     * @param queryDto {@link CasePaymentMainRecordQueryDto}
     * @return {@link List <CasePaymentMainRecordVo>} 缴款单信息
     * @author xiangyuyu
     * @date 2022-03-01 16:51
     */
    @Override
    public List<CasePaymentMainRecordVo> getPaymentChannelConfigInfo(CasePaymentMainRecordQueryDto queryDto) {
        String noticeNo = queryDto.getNoticeNo();
        if (ObjectUtils.isEmpty(noticeNo)) {
            throw new BusinessException("未指定缴款单号");
        }
        //先计算滞纳金，然后再获取缴款信息
        //this.zljMoney(queryDto);

        List<CasePaymentMainRecordVo> casePaymentMainRecordList = casePaymentMainRecordMapper.selectPaymentChannelConfigInfo(queryDto);
        casePaymentMainRecordList.forEach(e -> {
            if(Constant.STRING_3.equals(e.getStatus())){
                e.setErrorMsg("已线下缴款");
            }
            if(Constant.STRING_4.equals(e.getStatus())){
                e.setErrorMsg("该缴款单已失效");
            }
            String caseId = e.getCaseId();
            //获取案件主表信息
            CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);

            //查询对应处罚决定书是否送达，判断是否为分别处罚，如果是的话，需要传partyId
            CaseDocumentRecordDto dto = null;
            if(PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfo.getCasePartiesReasonType()) && HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())){
                dto = caseDocumentRecordService.selectCaseDocumentRecordByKindCodeAndPartyId(caseId, Constant.STRING_KIND_CODE_CFJDS, e.getPartyId());
            }else {
                dto = caseDocumentRecordService.getCaseDocumentRecordByKindCode(caseId, Constant.STRING_KIND_CODE_CFJDS);
            }
            if (!ObjectUtils.isEmpty(dto) && !DocumentStatusEnum.SENT.getCode().equals(dto.getDocumentSentStatus())) {
                e.setErrorMsg("请在处罚决定书送达之后再进行扫码支付操作");
            }
            //简易程序撤销后不可缴款
            if (!ObjectUtils.isEmpty(caseMainInfo) && CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())){
                if(CaseStatusEnum.SIMPLE_CASE_REVOKE.getCode().equals(caseMainInfo.getCaseStatus())) {
                    e.setErrorMsg("决定已撤销，不可进行缴款");
                }
            }

            //获取明细
            CasePaymentItemDetailQueryDto itemQuery = new CasePaymentItemDetailQueryDto();
            itemQuery.setPaymentId(e.getId());
            List<CasePaymentItemDetailVo> casePaymentItemDetailList = iCasePaymentItemDetailService.getCasePaymentItemDetailInfo(itemQuery);

            //判断是否开启滞纳金计算，并且有滞纳金
            SysDepartParam departParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfo.getCaseOrgCode(),null);
            if(!ObjectUtils.isEmpty(departParam) && Constant.WHETHER_STRING_YES.equals(departParam.getIsLateFee()) && StrUtil.isNotEmpty(e.getOverduePayment())){
                BigDecimal totalMoney = new BigDecimal(e.getTotalMoney());
                BigDecimal znj = new BigDecimal(e.getOverduePayment());
                String total = totalMoney.add(znj).toString();
                e.setTotalMoney(total);
                //明细处理
                if(!ObjectUtils.isEmpty(casePaymentItemDetailList)){
                    CasePaymentItemDetailVo casePaymentItemDetailVo = casePaymentItemDetailList.get(Constant.INTEGER_0);
                    casePaymentItemDetailVo.setChMoney(total);
                    casePaymentItemDetailVo.setChargeStandard(total);
                }
            }
            e.setCasePaymentItemDetailList(casePaymentItemDetailList);
        });
        return casePaymentMainRecordList;
    }

    /**
     * 描述：保存缴款单信息
     *
     * @param caseId              案件id
     * @param documentCatalogCode 文书目录编码
     * @param partyId             当事人id
     * @param caseType            案件类型
     * @return String 缴款单号
     * @author xiangyuyu
     * @date 2022-03-01 16:51
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveCasePaymentMainRecord(String caseId, String documentCatalogCode, String partyId, String caseType) {
        CasePaymentMainRecord casePaymentMainRecord = new CasePaymentMainRecord();
        casePaymentMainRecord.setPartyId(partyId);
        UserDTO userInfo = UserUtil.getUserInfo();
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new BusinessException("登录失效【获取缴款单】");
        }
        //获取缴款渠道相关配置信息，20220810改成取值案件关联机构编码
        CaseMainInfoVo caseMainInfoVo = caseMainInfoService.getCaseMainInfo(caseId);
        String orgCode = caseMainInfoVo.getCaseOrgCode();
        ConfigPaymentChannelInfoQueryDto queryDto = new ConfigPaymentChannelInfoQueryDto();
        // todo 当选择委托事项时，替换成委托单位的信息，可以用caseid查casereason表
        Example caseResonMainRecordExample = new Example(CaseReasonMainRecord.class);
        caseResonMainRecordExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("sxType",Constant.STRING_4);
        List<CaseReasonMainRecord> caseReasonMainRecords = caseReasonMainRecordMapper.selectByExample(caseResonMainRecordExample);
        if (CollUtil.isNotEmpty(caseReasonMainRecords)) {
            orgCode = caseReasonMainRecords.get(Constant.INTEGER_0).getClientOrgCode();
            queryDto.setChannelNo(CHANNEL_NO);
            queryDto.setOrgCode(orgCode);
            queryDto.setDeptCode(null);
        } else {
            queryDto.setChannelNo(CHANNEL_NO);
            queryDto.setOrgCode(orgCode);
            queryDto.setDeptCode(caseMainInfoVo.getCaseDeptCode());
        }
        List<ConfigPaymentChannelInfoVo> list = iConfigPaymentChannelInfoService.getPaymentChannelConfigInfo(queryDto);
        if (ObjectUtils.isEmpty(list) || list.size() == 0 || ObjectUtils.isEmpty(list.get(Constant.INTEGER_0))) {
            throw new BusinessException("未找到缴款渠道相关配置信息【" + orgCode + "】");
        }
        ConfigPaymentChannelInfoVo vo = list.get(Constant.INTEGER_0);
        String configRegiCode = vo.getRegiCode();
        if (ObjectUtils.isEmpty(configRegiCode)) {
            throw new BusinessException("未配置执收单位区域编码【" + orgCode + "】");
        }
        //区域编码取自配置表中的区域编码
        casePaymentMainRecord.setRegiCode(configRegiCode);
        casePaymentMainRecord.setEnterCode(vo.getEnterCode());
        casePaymentMainRecord.setEnterName(vo.getEnterName());
        String uid;
        boolean isExists = false;
        Example e = new Example(casePaymentMainRecord.getClass());
        e.createCriteria().andEqualTo("enterCode", casePaymentMainRecord.getEnterCode())
                .andEqualTo("caseId", caseId)
                .andEqualTo("regiCode", configRegiCode)
                .andEqualTo("partyId", partyId);
        List<CasePaymentMainRecord> records = casePaymentMainRecordMapper.selectByExample(e);
        //每次都重新生成缴款单号
        String paymentServiceNumber = punishDecideServiceImpl.generatePaymentServiceNumber();
        String noticeNo = CHANNEL_NO + paymentServiceNumber;
        if (!ObjectUtils.isEmpty(records) && records.size() > 0) {
            CasePaymentMainRecord record = records.get(Constant.INTEGER_0);
            uid = record.getId();
            /*paymentServiceNumber = record.getOriginalNoticeNo();
            noticeNo = record.getNoticeNo();*/
            isExists = true;
        } else {
            uid = BaseUtil.createUid();
            /*paymentServiceNumber = punishDecideServiceImpl.generatePaymentServiceNumber();
            noticeNo = CHANNEL_NO + paymentServiceNumber;*/
        }
        casePaymentMainRecord.setId(uid);
        casePaymentMainRecord.setCaseId(caseId);
        casePaymentMainRecord.setNoticeNo(noticeNo);
        casePaymentMainRecord.setChannelNo(CHANNEL_NO);
        casePaymentMainRecord.setOriginalNoticeNo(paymentServiceNumber);
        CasePartiesDetailInfoVo partyInfo = null;
        if(HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfoVo.getHandleType()) && PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfoVo.getCasePartiesReasonType())){
            //获取当事人信息
            partyInfo = iCasePartiesRecordService.getCasePartiesDetailInfoByCaseIdAndPartyId(caseId, partyId);
        }else {
            //获取当事人信息
            partyInfo = iCasePartiesRecordService.getCasePartiesDetailInfo(caseId);
        }
        String partyType = partyInfo.getPartyType();
        if (PartyTypeEnum.PERSON.getCode().equals(partyType)) {
            CasePartiesPersonInfoVo casePartiesPersonInfo = partyInfo.getCasePartiesPersonInfo();
            if (ObjectUtils.isEmpty(casePartiesPersonInfo)) {
                throw new BusinessException("未获取到当事人个人信息");
            }
            casePaymentMainRecord.setPayer(casePartiesPersonInfo.getName());
            casePaymentMainRecord.setPayerSfz(casePartiesPersonInfo.getCertNo());
        } else {
            CasePartiesLegalInfoVo casePartiesLegalInfo = partyInfo.getCasePartiesLegalInfo();
            if (ObjectUtils.isEmpty(casePartiesLegalInfo)) {
                throw new BusinessException("未获取到当事人法人信息");
            }
            //缴款人取企业名称-20220424
            casePaymentMainRecord.setPayer(casePartiesLegalInfo.getEntName());
            casePaymentMainRecord.setPayerSfz(casePartiesLegalInfo.getLegalCertNo());
        }
        LocalDateTime now = LocalDateTime.now();
        casePaymentMainRecord.setMakeDate(now.format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        casePaymentMainRecord.setMakeTime(now.format(DateTimeFormatter.ofPattern("HHmmss")));
        //<ISTRUENAME>1</ISTRUENAME>传1匹配不到商户,默认0
        casePaymentMainRecord.setIsTrueName(YesOrNoEnum.NO.getCode());

        //没收违法所得
        String confiscateIllegalMoney = null;
        //拟处罚金额
        String draftPunishMoney = null;
        boolean isNeedPartyId = caseMainInfoService.validateIsNeedPassPartyId(null, caseId);
        if (isNeedPartyId) {
            CaseMainDetailAuxiliaryInfoRequest request = new CaseMainDetailAuxiliaryInfoRequest(caseId, partyId);
            List<CaseMainDetailAuxiliaryInfo> caseMainDetailAuxiliaryInfoList = caseMainDetailAuxiliaryInfoService.getCaseMainDetailAuxiliaryInfo(request);
            if (!ObjectUtils.isEmpty(caseMainDetailAuxiliaryInfoList) && caseMainDetailAuxiliaryInfoList.size() > 0) {
                CaseMainDetailAuxiliaryInfo partyCaseInfo = caseMainDetailAuxiliaryInfoList.get(Constant.INTEGER_0);
                confiscateIllegalMoney = partyCaseInfo.getConfiscateIllegalMoney();
                draftPunishMoney = partyCaseInfo.getDraftPunishMoney();
            }
        } else {
            //简易程序查询简易详情表
            if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseType)) {
                CaseMainDetailSimpleInfo caseMainDetailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);

                //拟处罚金额
                draftPunishMoney = caseMainDetailSimpleInfo.getDraftPunishMoney();
            } else {
                CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectByPrimaryKey(caseId);
                //没收违法所得
                confiscateIllegalMoney = caseMainDetailInfo.getConfiscateIllegalMoney();
                //拟处罚金额
                draftPunishMoney = caseMainDetailInfo.getDraftPunishMoney();
            }
        }
        double confiscateIllegalMoneyD = 0D;
        double draftPunishMoneyD = 0D;
        if (!ObjectUtils.isEmpty(confiscateIllegalMoney)) {
            confiscateIllegalMoneyD = Double.parseDouble(confiscateIllegalMoney);
        }
        if (!ObjectUtils.isEmpty(draftPunishMoney)) {
            draftPunishMoneyD = Double.parseDouble(draftPunishMoney);
        }
        //罚款金额总计
        BigDecimal totalPunishMoney = BigDecimal.valueOf(confiscateIllegalMoneyD).add(BigDecimal.valueOf(draftPunishMoneyD));
        if (BigDecimal.valueOf(Constant.INTEGER_0).compareTo(totalPunishMoney) == 0) {
            log.info("处罚金额为0，不需要罚款,caseId:{}", caseId);
            return "";
        }
        casePaymentMainRecord.setTotalMoney(totalPunishMoney + "");
        // FIXME: 2022/3/17 缴款截止时间具体计算规则（收到xx决定书n日起）
        LocalDateTime deadline = now.plusDays(15);
        String deadLineYmd = deadline.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        //String deadLineHms = deadline.format(DateTimeFormatter.ofPattern("HHmmss"));
        //不设定截止日期信息-20220426
        casePaymentMainRecord.setExpiredPayDate("99991230");
        casePaymentMainRecord.setExpiredPayTime("235959");

        casePaymentMainRecord.setIsCountOverdue(Constant.STRING_0);
        //固定表现形式-6
        casePaymentMainRecord.setNoticeDis(Constant.STRING_6);
        casePaymentMainRecord.setOrgCode(orgCode);
        //默认未缴款
        casePaymentMainRecord.setStatus(null);
        if (isExists) {
            casePaymentMainRecordMapper.updateByExampleSelective(casePaymentMainRecord, e);
        } else {
            casePaymentMainRecordMapper.insertSelective(casePaymentMainRecord);
        }
        //保存案件缴款项目明细列表(执收项目信息)
        //没收违法所得
        CasePaymentItemDetail casePaymentItemDetail = new CasePaymentItemDetail();
        String paymentItemId = BaseUtil.createUid();
        casePaymentItemDetail.setId(paymentItemId);
        casePaymentItemDetail.setPaymentId(uid);

        String defaultChitCode = vo.getDefaultChitCode();
        if (ObjectUtils.isEmpty(defaultChitCode)) {
            throw new BusinessException("该机构未配置默认执收编码信息[" + orgCode + "]");
        }
        String defaultInitName = vo.getDefaultChitName();
        casePaymentItemDetail.setChitCode(defaultChitCode);
        casePaymentItemDetail.setChitName(ObjectUtils.isEmpty(defaultInitName) ? "罚没收入" : defaultInitName);
        if (ObjectUtils.isEmpty(confiscateIllegalMoney)) {
            confiscateIllegalMoney = Constant.STRING_0;
        }
        // FIXME: 2022/3/23 用填充totalMoney填充
        casePaymentItemDetail.setChMoney(totalPunishMoney + "");
        casePaymentItemDetail.setChargeStandard(totalPunishMoney + "");
        casePaymentItemDetail.setMetricUnit("元");
        casePaymentItemDetail.setChCount("1");

        Example e1 = new Example(casePaymentItemDetail.getClass());
        e1.createCriteria().andEqualTo("paymentId", casePaymentItemDetail.getPaymentId())
                .andEqualTo("chitCode", casePaymentItemDetail.getChitCode());
        int c1 = casePaymentItemDetailMapper.selectCountByExample(e1);
        if (c1 > 0) {
            casePaymentItemDetailMapper.updateByExampleSelective(casePaymentItemDetail, e1);
        } else {
            casePaymentItemDetailMapper.insertSelective(casePaymentItemDetail);
        }

        // FIXME: 2022/3/18 行政单位国有资产处置收入【暂时先将拟处罚金额放至该项】
        /*casePaymentItemDetail = new CasePaymentItemDetail();
        paymentItemId = BaseUtil.createUid();
        casePaymentItemDetail.setId(paymentItemId);
        casePaymentItemDetail.setPaymentId(uid);
        casePaymentItemDetail.setChitCode("06801805");
        casePaymentItemDetail.setChitName("行政单位国有资产处置收入");
        if(ObjectUtils.isEmpty(draftPunishMoney)){
            draftPunishMoney = Constant.STRING_0;
        }
        casePaymentItemDetail.setChMoney(draftPunishMoney);

        casePaymentItemDetail.setChargeStandard(confiscateIllegalMoney);
        casePaymentItemDetail.setMetricUnit("元");
        casePaymentItemDetail.setChCount("1");
        casePaymentItemDetailMapper.insertSelective(casePaymentItemDetail);*/
        //待缴费数据推送
        BusUnpayDataSyncModelDto busUnpayDataSyncModelDto=new BusUnpayDataSyncModelDto();
        busUnpayDataSyncModelDto.setDataType(Constant.STRING_1);//默认非税
        busUnpayDataSyncModelDto.setRegion(casePaymentMainRecord.getRegiCode());//行政区划
        //支付提供
        busUnpayDataSyncModelDto.setDeptId(casePaymentMainRecord.getEnterCode());
        busUnpayDataSyncModelDto.setDocNumber(noticeNo);//取值支付单号
        busUnpayDataSyncModelDto.setPaymentUnit(casePaymentMainRecord.getPayer());//缴款人（单位）
        busUnpayDataSyncModelDto.setExtraPaymentUnit("");//额外缴款 暂时不填
        busUnpayDataSyncModelDto.setPaymentTotal(new BigDecimal(casePaymentMainRecord.getTotalMoney()));
        busUnpayDataSyncModelDto.setPhone(casePaymentMainRecord.getPayerMobile());//todo 可能为空
        busUnpayDataSyncModelDto.setIdCard(casePaymentMainRecord.getPayerSfz());
        //暂时先不写
        busUnpayDataSyncModelDto.setNotifyUrl(notifyUrl);
        busUnpayDataSyncModelDto.setRemark("");
        busUnpayDataSyncModelDto.setIsApplyVirtualAccount(Constant.STRING_0);
        busUnpayDataSyncModelDto.setIsApplyPayCode(Constant.STRING_0);
        List<ChargeItem> items=new ArrayList<>();
        ChargeItem chargeItem=new ChargeItem();
        chargeItem.setItemCode(casePaymentItemDetail.getChitCode());
        chargeItem.setStandard(new BigDecimal(casePaymentItemDetail.getChargeStandard()));
        chargeItem.setBiNumber(new BigDecimal(Constant.STRING_1));
        chargeItem.setActualAmt(new BigDecimal(casePaymentItemDetail.getChargeStandard()));
        items.add(chargeItem);
        busUnpayDataSyncModelDto.setItems(items);
        JSONObject jsonObject =(JSONObject)JSONObject.toJSON(busUnpayDataSyncModelDto);
        try {
            BaseUtil.post(busUnpayDataSyncUrl, jsonObject);
        }catch (Exception exc){
            exc.printStackTrace();
            throw new BusinessException("缴费信息同步推送失败");
        }
        return noticeNo;
    }

    /**
     * 查询缴款单分页列表
     *
     * @param queryDto
     * @return
     */
    @Override
    public List<CasePaymentBillListVo> queryPaymentBillPageList(CasePaymentBillQueryDto queryDto) {
        this.setOrgAndDeptCode(queryDto);
        PageHelper.startPage(queryDto.getPageNum(), queryDto.getLength());
        List<CasePaymentBillListVo> list = casePaymentMainRecordMapper.queryPaymentBillPageList(queryDto);
        list.forEach(vo -> {
            //判断是否有滞纳金
            if(StrUtil.isNotEmpty(vo.getOverduePayment())){
                BigDecimal totalMoney = new BigDecimal(vo.getTotalMoney());
                BigDecimal znj = new BigDecimal(vo.getOverduePayment());
                String total = totalMoney.add(znj).toString();
                vo.setTotalMoney(total);
            }
            //获取是否支付状态
            /*CasePaymentResultRecord resultRecord = new CasePaymentResultRecord();
            resultRecord.setNoticeNo(vo.getNoticeNo());
            resultRecord.setIsDelete(Constant.STRING_0);
            int count = casePaymentResultRecordMapper.selectCount(resultRecord);
            if (count > 0) {
                vo.setPayStatus(Constant.STRING_1);
                vo.setPayStatusText("已支付");
            } else {
                vo.setPayStatus(Constant.STRING_2);
                vo.setPayStatusText("未支付");
            }*/
            vo.setPayStatusText(PayStatusEnum.getValueByCode(vo.getPayStatus()));
            if(StringUtils.isBlank(vo.getPayStatus())){
                vo.setPayStatusText("待支付");
            }
            //案件类型
            vo.setCaseType(CaseTypeEnum.getValueByCode(vo.getCaseType()));
            //当事人类型
            vo.setPartyType(Constant.STRING_1);
            if (!ObjectUtils.isEmpty(vo.getPartyId()) && vo.getPartyId().contains(",")) {
                //多当事人
                Example query = new Example(CasePartiesRecord.class);
                query.createCriteria().andEqualTo("caseId", vo.getCaseId()).andEqualTo("partyType", "2").andEqualTo("status", "1");
                List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(query);
                if(partiesRecords != null && !partiesRecords.isEmpty()){
                    CasePartiesRecord casePartiesRecord = partiesRecords.get(0);
                    //如果是法人
                    if(casePartiesRecord != null && Constant.STRING_2.equals(casePartiesRecord.getPartyType())){
                        vo.setPartyType(Constant.STRING_2);
                        vo.setPartyIdentityCode(casePartiesRecord.getPartyIdentityCode());
                        //查询企业名称
                        CasePartiesLegalInfo casePartiesLegalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(casePartiesRecord.getPartyId());
                        vo.setPayer(casePartiesLegalInfo.getEntName());
                    }
                }
            } else {
                Example query = new Example(CasePartiesRecord.class);
                query.createCriteria().andEqualTo("caseId", vo.getCaseId()).andEqualTo("status", "1");
                List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(query);
                if(partiesRecords != null && !partiesRecords.isEmpty()){
                    CasePartiesRecord casePartiesRecord = partiesRecords.get(0);
                    //如果是法人
                    if(casePartiesRecord != null && Constant.STRING_2.equals(casePartiesRecord.getPartyType())){
                        vo.setPartyType(Constant.STRING_2);
                        vo.setPartyIdentityCode(casePartiesRecord.getPartyIdentityCode());
                        //查询企业名称
                        CasePartiesLegalInfo casePartiesLegalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(casePartiesRecord.getPartyId());
                        vo.setPayer(casePartiesLegalInfo.getEntName());
                    }
                }
            }

        });
        return list;
    }

    public void exportPaymentBillList(CasePaymentBillQueryDto queryDto, HttpServletResponse response) throws Exception {
        List<CasePaymentBillListExportVo> exportVos = new ArrayList<>();
        this.setOrgAndDeptCode(queryDto);
        List<CasePaymentBillListVo> list = casePaymentMainRecordMapper.queryPaymentBillPageList(queryDto);
        list.forEach(vo -> {
            //获取是否支付状态
            vo.setPayStatusText(PayStatusEnum.getValueByCode(vo.getPayStatus()));
            if(StringUtils.isBlank(vo.getPayStatus())){
                vo.setPayStatusText("待支付");
            }
            //案件类型
            vo.setCaseType(CaseTypeEnum.getValueByCode(vo.getCaseType()));
            //当事人类型
            vo.setPartyType(Constant.STRING_1);
            if (!ObjectUtils.isEmpty(vo.getPartyId()) && vo.getPartyId().contains(",")) {
                //多当事人
                Example query = new Example(CasePartiesRecord.class);
                query.createCriteria().andEqualTo("caseId", vo.getCaseId()).andEqualTo("partyType", "2").andEqualTo("status", "1");
                List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(query);
                if(partiesRecords != null && !partiesRecords.isEmpty()){
                    CasePartiesRecord casePartiesRecord = partiesRecords.get(0);
                    //如果是法人
                    if(casePartiesRecord != null && Constant.STRING_2.equals(casePartiesRecord.getPartyType())){
                        vo.setPartyType(Constant.STRING_2);
                        vo.setPartyIdentityCode(casePartiesRecord.getPartyIdentityCode());
                        //查询企业名称
                        CasePartiesLegalInfo casePartiesLegalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(casePartiesRecord.getPartyId());
                        vo.setPayer(casePartiesLegalInfo.getEntName());
                    }
                }
            } else {
                Example query = new Example(CasePartiesRecord.class);
                query.createCriteria().andEqualTo("caseId", vo.getCaseId()).andEqualTo("status", "1");
                List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(query);
                if(partiesRecords != null && !partiesRecords.isEmpty()){
                    CasePartiesRecord casePartiesRecord = partiesRecords.get(0);
                    //如果是法人
                    if(casePartiesRecord != null && Constant.STRING_2.equals(casePartiesRecord.getPartyType())){
                        vo.setPartyType(Constant.STRING_2);
                        vo.setPartyIdentityCode(casePartiesRecord.getPartyIdentityCode());
                        //查询企业名称
                        CasePartiesLegalInfo casePartiesLegalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(casePartiesRecord.getPartyId());
                        vo.setPayer(casePartiesLegalInfo.getEntName());
                    }
                }
            }

            CasePaymentBillListExportVo exportVo = new CasePaymentBillListExportVo();
            BeanUtils.copyProperties(vo, exportVo);
            if (!ObjectUtils.isEmpty(vo.getCreateRecordTime())) {
                exportVo.setCreateRecordTimeStr(DateUtil.formatLocalDateTimeString1(vo.getCreateRecordTime()));
            }
            if (!ObjectUtils.isEmpty(vo.getPayTime())) {
                exportVo.setPayTimeStr(DateUtil.formatLocalDateTimeString1(vo.getPayTime()));
            }
            exportVos.add(exportVo);
        });

        //设置字段名称
        List<Map<String, String>> headList = new ArrayList<>();
        headList.add(Collections.singletonMap("payer", "缴款人名称"));
        headList.add(Collections.singletonMap("payStatusText", "状态"));
        headList.add(Collections.singletonMap("noticeNo", "缴款单号"));
        headList.add(Collections.singletonMap("caseNumber", "案件编号"));
        headList.add(Collections.singletonMap("documentNumber", "文书关联编号"));
        headList.add(Collections.singletonMap("handlePersonName", "承办人"));
        headList.add(Collections.singletonMap("caseDeptName", "承办部门"));
        headList.add(Collections.singletonMap("createRecordTimeStr", "缴款单生成日期"));
        headList.add(Collections.singletonMap("payTimeStr", "缴款日期"));
        headList.add(Collections.singletonMap("tradeName", "代收机构"));
        headList.add(Collections.singletonMap("wayName", "支付方式"));
        headList.add(Collections.singletonMap("chCount", "项目数量"));
        headList.add(Collections.singletonMap("totalMoney", "合计金额"));

        String fileName = "缴款单列表";


        ExcelUtils.ExportList(exportVos, headList, fileName, response);

    }

    /**
     * 查询支付方式和支付机构列表
     *
     * @return
     */
    @Override
    public CasePaymentBillTradeWayVo queryPaymentBillTradeWayList() {
        CasePaymentBillTradeWayVo reVo = new CasePaymentBillTradeWayVo();
        reVo.setPayTradeList(casePaymentMainRecordMapper.getPaymentTradeList());
        reVo.setPayWayList(casePaymentMainRecordMapper.getPaymentWayList());
        return reVo;
    }

    /**
     * 专题查询-缴款单查询-查询当地财政部门是否开出发票
     * @param noticeNo
     * @return
     */
    @Override
    public List<String> getElectricInvoiceByNoticeNo(String noticeNo){
        try {
            //查询支付主表
            Example exampleMain = new Example(CasePaymentMainRecord.class);
            exampleMain.createCriteria().andEqualTo("noticeNo", noticeNo);
            List<CasePaymentMainRecord> mainRecords = casePaymentMainRecordMapper.selectByExample(exampleMain);
            if(ObjectUtils.isEmpty(mainRecords)){
                return null;
            }
            //查询支付结果表
            Example exampleResult = new Example(CasePaymentResultRecord.class);
            exampleResult.createCriteria().andEqualTo("noticeNo", noticeNo).andEqualTo("isDelete", Constant.WHETHER_STRING_NO);
            List<CasePaymentResultRecord> resultRecords = casePaymentResultRecordMapper.selectByExample(exampleResult);
            if(ObjectUtils.isEmpty(resultRecords)){
                return null;
            }
            CasePaymentMainRecord casePaymentMainRecord = mainRecords.get(Constant.INTEGER_0);
            CasePaymentResultRecord casePaymentResultRecord = resultRecords.get(Constant.INTEGER_0);
            //查询发票--直接复用之前的逻辑
            ElectricInvoiceRequest request = new ElectricInvoiceRequest();
            request.setResponseFileFormatType("2");
            request.setEnterCode(casePaymentMainRecord.getEnterCode());
            request.setCertificateNo(casePaymentResultRecord.getCertificateNo());
            request.setCheckCode(casePaymentResultRecord.getCheckCode());
            return electricInvoiceInterface.getElectricInvoice(request);
        }catch (Exception e){
            log.error("-----------查询电子发票报错------------", e);
            return null;
        }
    }

    /**
     * 描述：更新案件缴费
     * @param mainRecord
     * @return
     * @author wangfawei
     * @date  2022-12-6
     */
    @Override
    public int updateCasePaymentMainRecord(CasePaymentMainRecord mainRecord) {
        return casePaymentMainRecordMapper.updateByPrimaryKeySelective(mainRecord);
    }
    /**
     * 描述：查询案件缴费信息
     * @param noticeNo 缴款单号
     * @return
     * @author wangfawei
     * @date  2022-12-6
     */
    @Override
    public CasePaymentMainRecord getCasePaymentMainRecord(String caseId,String noticeNo) {
        Example query = new Example(CasePaymentMainRecord.class);
        query.createCriteria().andEqualTo("caseId", caseId).andEqualTo("noticeNo", noticeNo);
        List<CasePaymentMainRecord> partiesRecords = casePaymentMainRecordMapper.selectByExample(query);
        if(partiesRecords.size()>0){
            return partiesRecords.get(0);
        }
        return null;
    }

    /**
     * 设置机构和部门参数
     *
     * @param queryDto
     */
    private void setOrgAndDeptCode(CasePaymentBillQueryDto queryDto) {
        queryDto.setOrgType(0);
        if (!StrUtil.isEmpty(queryDto.getOrgCode())) {
            List<String> orgCodeList = new ArrayList<>();
            List<String> deptCodeList = new ArrayList<>();
            String[] str = queryDto.getOrgCode().split(",");

            for (String s : str) {
                if (s.indexOf("_") > 0) {
                    orgCodeList.add(s);
                } else {
                    orgCodeList.add(s);
                }
            }
            if (orgCodeList.size() > 0 && deptCodeList.size() > 0) {
                queryDto.setOrgType(1);
            } else if (orgCodeList.size() > 0) {
                queryDto.setOrgType(2);
            } else if (deptCodeList.size() > 0) {
                queryDto.setOrgType(3);
            }
            queryDto.setOrgCodeList(orgCodeList);
            queryDto.setDeptCodeList(deptCodeList);
        }
    }

    @Override
    public void updateCasePaymentMainRecordStatus (CasePaymentMainRecordStatusUpdateDto updateDto) {
        if (ObjectUtils.isEmpty(updateDto.getCaseId())) {
            throw new BusinessException("案件id不能为空");
        }
        if (ObjectUtils.isEmpty(updateDto.getPartyId())) {
            throw new BusinessException("当事人id不能为空");
        }
        if (ObjectUtils.isEmpty(updateDto.getStatus())) {
            throw new BusinessException("缴款状态不能为空");
        }
        Example updateE = new Example(CasePaymentMainRecord.class);
        updateE.createCriteria().andEqualTo("caseId", updateDto.getCaseId())
                .andEqualTo("partyId", updateDto.getPartyId());

        CasePaymentMainRecord mainRecord = new CasePaymentMainRecord();
        mainRecord.setStatus(updateDto.getStatus());
        casePaymentMainRecordMapper.updateByExampleSelective(mainRecord, updateE);
    }

    /**
     * 描述： 根据缴款单号更新缴款状态
     *
     * @author: zhengqiang
     * @date: 2023/1/16
     * @param: noticeNo
     * @param: status
     * @return {@link int}
     **/
    @Override
    public int updateCasePaymentMainRecordStatusByNoticeNo(String noticeNo, String status) {
        if (ObjectUtils.isEmpty(noticeNo)) {
            throw new BusinessException("缴款单号不能为空");
        }
        Example updateE = new Example(CasePaymentMainRecord.class);
        updateE.createCriteria().andEqualTo("noticeNo", noticeNo);

        CasePaymentMainRecord mainRecord = new CasePaymentMainRecord();
        mainRecord.setStatus(status);
        return casePaymentMainRecordMapper.updateByExampleSelective(mainRecord, updateE);
    }

    /**
     * 根据caseId获取未缴款信息
     * @author liyafeng
     * @date 2023/6/30
      * @param caseId
     * @return {@link CasePaymentMainRecord}
     */
    @Override
    public CasePaymentMainRecord getCasePaymentMainRecord(String caseId) {
        Example query = new Example(CasePaymentMainRecord.class);
        query.createCriteria().andEqualTo("caseId", caseId).andIsNull("status");
        List<CasePaymentMainRecord> partiesRecords = casePaymentMainRecordMapper.selectByExample(query);
        if(partiesRecords.size()>0){
            return partiesRecords.get(0);
        }
        return null;
    }

    /**
     *  是否加罚款计算滞纳金
     *
     */
    private String zljMoney(CasePaymentMainRecordQueryDto saveDto){
        try {
            //根据缴款单号，获取caseId
            CasePaymentMainRecord recordParam = new CasePaymentMainRecord();
            recordParam.setNoticeNo(saveDto.getNoticeNo());
            List<CasePaymentMainRecord> records = casePaymentMainRecordMapper.select(recordParam);
            if(ObjectUtils.isEmpty(records)){
                return null;
            }
            CasePaymentMainRecord casePaymentMainRecord = records.get(Constant.INTEGER_0);
            if(StrUtil.isNotEmpty(casePaymentMainRecord.getStatus())){
                return null;
            }
            CaseMainInfoVo caseMainInfoVo = caseMainInfoService.getCaseMainInfo(casePaymentMainRecord.getCaseId());
            if(ObjectUtils.isEmpty(caseMainInfoVo)){
                return null;
            }
            SysDepartParam departParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfoVo.getCaseOrgCode(),null);
            if(ObjectUtils.isEmpty(departParam) || Constant.WHETHER_STRING_NO.equals(departParam.getIsLateFee())){
                return null;
            }
            CaseDocumentRecordQueryDto queryDto = new CaseDocumentRecordQueryDto();
            queryDto.setCaseId(casePaymentMainRecord.getCaseId());
            queryDto.setDocumentKindCode(Constant.STRING_KIND_CODE_CFJDS);
            queryDto.setIsQueryDocumentApprovalTimeNotNull(YesOrNoEnum.YES.getCode());
            if(PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfoVo.getCasePartiesReasonType()) && HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfoVo.getHandleType())){
                queryDto.setPartyId(casePaymentMainRecord.getPartyId());
            }
            List<CaseDocumentRecordVo> documentRecordList = caseDocumentRecordService.getCaseDocumentRecordList(queryDto);
            if(ObjectUtils.isEmpty(documentRecordList)){
                return null;
            }

            String draftPunishMoneyTemp = "";
            //判断是否分别处罚
            if(PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfoVo.getCasePartiesReasonType()) && HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfoVo.getHandleType())){
                CaseMainDetailAuxiliaryInfoRequest request = new CaseMainDetailAuxiliaryInfoRequest();
                request.setCaseId(casePaymentMainRecord.getCaseId());
                request.setPartyId(casePaymentMainRecord.getPartyId());
                List<CaseMainDetailAuxiliaryInfo> list = caseMainDetailAuxiliaryInfoService.getCaseMainDetailAuxiliaryInfo(request);
                if(ObjectUtil.isNotEmpty(list)){
                    draftPunishMoneyTemp = list.get(Constant.INTEGER_0).getDraftPunishMoney();
                }
            }else {
                CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailInfoByCaseId(casePaymentMainRecord.getCaseId());
                if(!ObjectUtils.isEmpty(caseMainDetailInfo)) {
                    draftPunishMoneyTemp = caseMainDetailInfo.getDraftPunishMoney();
                }
            }

            CaseDocumentRecordVo caseDocumentRecordVo = documentRecordList.get(Constant.INTEGER_0);
            //int day = DateUtil.getBetweenDays(DateUtil.formatLocalDateTimeString1(caseDocumentRecordVo.getSentTime()), DateUtil.getCurrentTime());
            Date sentTime = cn.hutool.core.date.DateUtil.parseDate(DateUtil.formatLocalDateTimeString1(caseDocumentRecordVo.getSentTime()));
            long day = cn.hutool.core.date.DateUtil.betweenDay(sentTime, new Date(), true);
            if (day > 15) {
                long addDay = day - 15;
                //滞纳金，不需要小数点
                BigDecimal bigDecimal = new BigDecimal(draftPunishMoneyTemp);
                int draftPunishMoney = bigDecimal.intValue();
                long money = (draftPunishMoney * addDay * 3) / 100;
                if (money > draftPunishMoney) {
                    money = draftPunishMoney;
                }
                casePaymentMainRecord.setOverduePayment(String.valueOf(money));
                casePaymentMainRecord.setOverdueTime(DateUtil.getCurrLocalDateTime());
                casePaymentMainRecordService.updateCasePaymentMainRecord(casePaymentMainRecord);
                return String.valueOf(money);
            }else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("计算滞纳金失败"+e.getMessage());
            return null;
        }
    }

}